#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#define N 128

//21-fifo_write  send     recv
//argv[0]      argv[1]  argv[2]
int main(int argc, char const *argv[])
{
    char buf[N] = {0};
    int ret, fd_send, fd_recv;
    if (argc != 3)
    {
        fprintf(stderr, "错误运行程序时请代入参数(./21-fifo_write send recv)\n");
        exit(-1);
    }
    //测试这个文件是否存在，存在返回为0，错误返回-1
    //文件存在的话，就不需要创建管道
    //文件不存在则创建管道文件
    if (access(argv[1], F_OK) != 0) //文件不存在
    {
        ret = mkfifo(argv[1], 0664);
        if (ret < 0)
        {
            perror("mkfifo1");
            exit(-1);
        }
    }
    if (access(argv[2], F_OK) != 0) //文件不存在
    {
        ret = mkfifo(argv[2], 0664);
        if (ret < 0)
        {
            perror("mkfifo2");
            exit(-1);
        }
    }

    fd_send = open(argv[1], O_RDWR);
    if (fd_send < 0)// file descriptor
    {
        perror("open");
        exit(-1);
    }
    fd_recv = open(argv[2], O_RDWR);
    if (fd_recv < 0)// file descriptor
    {
        perror("open");
        exit(-1);
    }

    printf("fd_send=%d\n", fd_send);
    printf("fd_recv=%d\n", fd_recv);

    while (1)
    {
        printf(">:");
        fgets(buf, N, stdin);
        buf[strlen(buf) - 1] = '\0'; //去除'\n'
        ret = write(fd_send, buf, N);
        if (ret < 0)
        {
            perror("write");
            exit(-1);
        }
        if (strncmp(buf, "quit", 4) == 0)
            break;
        buf[strlen(buf) - 1] = '\0';
        ret = read(fd_recv, buf, N);
        if (ret < 0)
        {
            perror("read");
            exit(-1);
        }
        if (strncmp(buf, "quit", 4) == 0)
            break;
        printf("buf=%s\n", buf);
    }
    close(fd_send);
    close(fd_recv);

    return 0;
}
